#include "history.h"
#include "ui_history.h"

History::History(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::History)
{
    ui->setupUi(this);
    setupRealtimeDataDemo(ui->customPlot);
        ui->customPlot->replot();

//        ui->checkBox_temp->setChecked(true);
//        ui->checkBox_hui->setChecked(true);

        connect(ui->comboBox,SIGNAL(currentIndexChanged(int)),
                    this,SLOT(query(int)));
//        connect(ui->pushButton,SIGNAL(clicked()),
//                this,SLOT(query(int)));
//        connect(this,SIGNAL(table(DOUBLE)),
//                this,SLOT(realtimeDataSlot(DOUBLE)));
//        // 创建定时器对象
//        timer = new QTimer(this);
//        connect(timer, SIGNAL(timeout()),
//                this,SLOT(realtimeDataSlot()));
}

History::~History()
{
    delete ui;
}


void History::query(int i)
{
    if(i == 1)
    {
//        ui->pushButton->setEnabled(true);
        // 创建 JSON 对象
        QJsonObject jsonObj;
        jsonObj["type"] = 4;
        QJsonObject dataObj;
        dataObj["key"] = 302;
        // 创建限制数组
        QJsonArray limitArray;
        qint64 time = QDateTime::currentMSecsSinceEpoch()/1000;
        qint64 time1 = time - 60*5;


        limitArray.append(time1);
        limitArray.append(time);
        dataObj["limit"] = limitArray;
        // 将 dataObj 添加到主对象中
        jsonObj["data"] = dataObj;
        // 将 JSON 对象转换为 JSON 文档
        QJsonDocument jsonDoc(jsonObj);
        // 将 JSON 文档转换为字符串
        QByteArray jsonBytes = jsonDoc.toJson(QJsonDocument::Indented);

        qDebug() << jsonBytes;
        emit history(jsonBytes);
    }
    else if(i == 2)
    {
//        ui->pushButton->setEnabled(true);
        // 创建 JSON 对象
        QJsonObject jsonObj;
        jsonObj["type"] = 4;
        QJsonObject dataObj;
        dataObj["key"] = 303;
        // 创建限制数组
        QJsonArray limitArray;
        qint64 time = QDateTime::currentMSecsSinceEpoch()/1000;
        qint64 time1 = time - 60*5;


        limitArray.append(time1);
        limitArray.append(time);
        dataObj["limit"] = limitArray;
        // 将 dataObj 添加到主对象中
        jsonObj["data"] = dataObj;
        // 将 JSON 对象转换为 JSON 文档
        QJsonDocument jsonDoc(jsonObj);
        // 将 JSON 文档转换为字符串
        QByteArray jsonBytes = jsonDoc.toJson(QJsonDocument::Indented);

        qDebug() << jsonBytes;
        emit history(jsonBytes);
    }
    else if(i == 3)
    {
//        ui->pushButton->setEnabled(true);
        // 创建 JSON 对象
        QJsonObject jsonObj;
        jsonObj["type"] = 4;
        QJsonObject dataObj;
        dataObj["key"] = 101;
        // 创建限制数组
        QJsonArray limitArray;
        qint64 time = QDateTime::currentMSecsSinceEpoch()/1000;
        qint64 time1 = time - 60*5;


        limitArray.append(time1);
        limitArray.append(time);
        dataObj["limit"] = limitArray;
        // 将 dataObj 添加到主对象中
        jsonObj["data"] = dataObj;
        // 将 JSON 对象转换为 JSON 文档
        QJsonDocument jsonDoc(jsonObj);
        // 将 JSON 文档转换为字符串
        QByteArray jsonBytes = jsonDoc.toJson(QJsonDocument::Indented);

        qDebug() << jsonBytes;
        emit history(jsonBytes);
    }
    else if(i == 4)
    {
//        ui->pushButton->setEnabled(true);
        // 创建 JSON 对象
        QJsonObject jsonObj;
        jsonObj["type"] = 4;
        QJsonObject dataObj;
        dataObj["key"] = 102;
        // 创建限制数组
        QJsonArray limitArray;
        qint64 time = QDateTime::currentMSecsSinceEpoch()/1000;
        qint64 time1 = time - 60*5;


        limitArray.append(time1);
        limitArray.append(time);
        dataObj["limit"] = limitArray;
        // 将 dataObj 添加到主对象中
        jsonObj["data"] = dataObj;
        // 将 JSON 对象转换为 JSON 文档
        QJsonDocument jsonDoc(jsonObj);
        // 将 JSON 文档转换为字符串
        QByteArray jsonBytes = jsonDoc.toJson(QJsonDocument::Indented);

        qDebug() << jsonBytes;
        emit history(jsonBytes);
    }
    else if(i == 5)
    {
//        ui->pushButton->setEnabled(true);
        // 创建 JSON 对象
        QJsonObject jsonObj;
        jsonObj["type"] = 4;
        QJsonObject dataObj;
        dataObj["key"] = 104;
        // 创建限制数组
        QJsonArray limitArray;
        qint64 time = QDateTime::currentMSecsSinceEpoch()/1000;
        qint64 time1 = time - 60*5;


        limitArray.append(time1);
        limitArray.append(time);
        dataObj["limit"] = limitArray;
        // 将 dataObj 添加到主对象中
        jsonObj["data"] = dataObj;
        // 将 JSON 对象转换为 JSON 文档
        QJsonDocument jsonDoc(jsonObj);
        // 将 JSON 文档转换为字符串
        QByteArray jsonBytes = jsonDoc.toJson(QJsonDocument::Indented);

        qDebug() << jsonBytes;
        emit history(jsonBytes);
    }
//    else
//    {
//        ui->pushButton->setEnabled(false);
//    }
}

void History::hisSlot(QByteArray msg)
{
    qDebug() << "历史反序列化\n";
    QJsonParseError error;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(msg, &error);

    // 检查解析是否成功
    if (error.error != QJsonParseError::NoError) {
        qDebug().noquote() << "Error parsing JSON:" << error.errorString();
        return ;
    }

    // 获取 JSON 文档的根对象
    QJsonObject jsonObj = jsonDoc.object();

    // 从根对象中提取数据
    int type = jsonObj["type"].toInt();
    int result = jsonObj["result"].toInt();
    int key = jsonObj["key"].toInt();

    QJsonArray dataArray = jsonObj["data"].toArray();

    // 遍历数据数组
    qDebug().noquote() << "Deserialized JSON:";
    qDebug().noquote() << "type:" << type;
    qDebug().noquote() << "result:" << result;
    qDebug().noquote() << "key:" << key;

    qDebug().noquote() << "Data:";
    if(type == 4)
    {
    for (const auto& item : dataArray)
    {
     QJsonObject dataObj = item.toObject();
     double time = dataObj["time"].toDouble();
     QString val = dataObj["val"].toString();
     qDebug().noquote() << "time:" << time << ", val:" << val;
     value = val.toDouble();
     qDebug() << value ;
     qDebug() << time;
//     emit table(value);
//     timer->start(500);
     realtimeDataSlot(value,time);
    }
    }
}

void History::paintEvent(QPaintEvent *event)
{
    //
    QPainter painter(this);
    QPixmap map(":/new/prefix1/00.png");
    // 绘制图片
    // 参数1、2 横轴及纵轴坐标
    // 参数3、4 绘制的宽高
    // 参数5    绘制的内容
    painter.drawPixmap(0,0,width(),height(),map);
}



//画图初始化
void History::setupRealtimeDataDemo(QCustomPlot *customPlot)
{
//#if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
  //QMessageBox::critical(this, "", "You're using Qt < 4.7, the realtime data demo needs functions that are available with Qt 4.7 to work properly");
//#endif
  //demoName = "Real Time Data Demo";

  // include this section to fully disable antialiasing for higher performance:
  /*
  customPlot->setNotAntialiasedElements(QCP::aeAll);
  QFont font;
  font.setStyleStrategy(QFont::NoAntialias);
  customPlot->xAxis->setTickLabelFont(font);
  customPlot->yAxis->setTickLabelFont(font);
  customPlot->legend->setFont(font);
  */
  customPlot->addGraph(); // blue line
  customPlot->graph(0)->setPen(QPen(Qt::blue));
  customPlot->graph(0)->setName("数据");
  //customPlot->graph(0)->setBrush(QBrush(QColor(240, 255, 200)));
  //customPlot->graph(0)->setAntialiasedFill(false);
//  customPlot->addGraph(); // red line
//  customPlot->graph(1)->setPen(QPen(Qt::red));
//  customPlot->graph(1)->setName("hui");
  //customPlot->graph(0)->setChannelFillGraph(customPlot->graph(1));


  customPlot->xAxis->setTickLabelType(QCPAxis::ltDateTime);
  customPlot->xAxis->setDateTimeFormat("hh:mm:ss");
  customPlot->xAxis->setAutoTickStep(false);
  customPlot->xAxis->setTickStep(2);
  customPlot->axisRect()->setupFullAxesBox();

  // make left and bottom axes transfer their ranges to right and top axes:
  //connect(customPlot->xAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->xAxis2, SLOT(setRange(QCPRange)));
  //connect(customPlot->yAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->yAxis2, SLOT(setRange(QCPRange)));

  // setup a timer that repeatedly calls MainWindow::realtimeDataSlot:
  connect(&dataTimer, SIGNAL(timeout()), this, SLOT(realtimeDataSlot()));
  dataTimer.start(0); // Interval 0 means to refresh as fast as possible
  customPlot->legend->setVisible(true);



}

void History::realtimeDataSlot(DOUBLE value,DOUBLE key)
{
    //key的单位是秒
//    double key = QDateTime::currentDateTime().toMSecsSinceEpoch()/1000.0;

    qsrand(QTime::currentTime().msec() + QTime::currentTime().second() * 10000);
    //使用随机数产生两条曲线
//    double value0 = qrand() % 100;
//    double value1 = qrand() % 80;
//    if (ui->checkBox_temp->isChecked())
    qDebug() << value ;
        ui->customPlot->graph(0)->addData(key, value);//添加数据1到曲线1
//    if (ui->checkBox_hui->isChecked())
//        ui->customPlot->graph(1)->addData(key, value1);//添加数据2到曲线2
    //删除8秒之前的数据。这里的8要和下面设置横坐标宽度的8配合起来
    //才能起到想要的效果，可以调整这两个值，观察显示的效果。
    ui->customPlot->graph(0)->removeDataBefore(key-360);
//    ui->customPlot->graph(1)->removeDataBefore(key-8);

      //自动设定graph(1)曲线y轴的范围，如果不设定，有可能看不到图像
//也可以用ui->customPlot->yAxis->setRange(up,low)手动设定y轴范围
    ui->customPlot->graph(0)->rescaleValueAxis();
//    ui->customPlot->graph(1)->rescaleValueAxis(true);

    //这里的8，是指横坐标时间宽度为8秒，如果想要横坐标显示更多的时间
    //就把8调整为比较大到值，比如要显示60秒，那就改成60。
//    这时removeDataBefore(key-8)中的8也要改成60，否则曲线显示不完整。
    ui->customPlot->xAxis->setRange(key, 360, Qt::AlignRight);//设定x轴的范围
    double tickStep = 40.0; // 设置刻度间隔为1
    ui->customPlot->xAxis->setTickStep(tickStep); // 设置刻度步长
//    ui->customPlot->yAxis->setRange(200, 300);//设定x轴的范围
//    tickStep = 20.0; // 设置刻度间隔为1
//    ui->customPlot->yAxis->setTickStep(tickStep); // 设置刻度步长
    ui->customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables); //QCP::iRangeDrag | QCP::iRangeZoom |
    ui->customPlot->replot();
}
